<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>执行巡检</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <!-- 巡检基本信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="巡检单号">{{ inspectionRecord.recordCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ inspectionRecord.equipmentName }}</el-descriptions-item>
        <el-descriptions-item label="巡检人员">{{ inspectionRecord.inspectorName }}</el-descriptions-item>
        <el-descriptions-item label="巡检日期">{{ parseTime(inspectionRecord.inspectionDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="计划名称">{{ inspectionRecord.planName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusType">{{ statusText }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">巡检日期</el-divider>
      
      <!-- 日期选择区域 -->
      <div class="calendar-container">
        <el-alert
          title="提示：已巡检的日期可以点击进行修改"
          type="info"
          :closable="false"
          style="margin-bottom: 10px;">
        </el-alert>
        
        <!-- 自定义表格实现的日历 -->
        <div class="simple-calendar">
          <div class="calendar-header">
            <el-button icon="el-icon-arrow-left" size="mini" @click="changeMonth(-1)"></el-button>
            <span class="month-title">{{ parseTime(currentMonth, '{y}年{m}月') }}</span>
            <el-button icon="el-icon-arrow-right" size="mini" @click="changeMonth(1)"></el-button>
          </div>
          
          <table class="calendar-table">
            <thead>
              <tr>
                <th>周日</th>
                <th>周一</th>
                <th>周二</th>
                <th>周三</th>
                <th>周四</th>
                <th>周五</th>
                <th>周六</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(week, weekIndex) in calendarData" :key="'week-' + weekIndex">
                <td 
                  v-for="(day, dayIndex) in week" 
                  :key="'day-' + weekIndex + '-' + dayIndex"
                  :class="[
                    'calendar-cell',
                    { 'is-today': day.isToday },
                    { 'inspection-date': day.isInspection },
                    { 'completed-date': day.isCompleted },
                    { 'selected-date': day.isSelected },
                    { 'other-month': !day.isCurrentMonth }
                  ]"
                  @click="day.isCurrentMonth && handleCellClick(day)"
                >
                  <div class="cell-content" v-if="day.date">
                    <span class="date-text">{{ day.dayOfMonth }}</span>
                    <span v-if="day.isInspection" class="inspection-tag" :class="{ 'is-completed': day.isCompleted }">
                      {{ day.isCompleted ? '已巡检' : '未巡检' }}
                    </span>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <el-divider content-position="center">巡检项目列表</el-divider>
      
      <div v-if="!selectedDateRecord">
        <el-alert
          title="请先在日历中选择一个巡检日期"
          type="info"
          :closable="false">
        </el-alert>
      </div>
      
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 当前选中日期 -->
        <div class="selected-date-info">
          <el-alert
            :key="'selected-date-' + (selectedDate ? parseTime(selectedDate, '{y}{m}{d}') : 'none')"
            :title="'当前正在执行 ' + parseTime(selectedDate, '{y}-{m}-{d}') + ' 的巡检'"
            type="success"
            :closable="false">
          </el-alert>
        </div>
        
        <!-- 巡检项目表格 -->
        <el-table 
          :data="inspectionItems" 
          border 
          style="width: 100%; margin-bottom: 20px;"
          v-loading="loading"
        >
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column prop="itemName" label="巡检项目" min-width="150" />
          <el-table-column label="标准值/范围" min-width="150">
            <template slot-scope="scope">
              {{ scope.row.standardValue || scope.row.itemStandard || scope.row.normalRange || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="checkMethod" label="巡检方法" min-width="150" />
          <el-table-column label="巡检结果" width="100" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isPassed" @change="handleCheckboxChange(scope.row)">通过</el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" type="textarea" :rows="1" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
        </el-table>

        <!-- 巡检备注 -->
        <el-form-item label="巡检备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" :rows="3" placeholder="请输入巡检备注"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveDateResult">保存当前日期的巡检结果</el-button>
          <el-button type="success" @click="submitForm" :disabled="!isAllDatesCompleted">提交整个巡检单</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getInspectionRecord, updateInspectionRecord } from "@/api/sb/inspectionRecord";
import { getDetailsByRecordId } from "@/api/sb/inspectionDetail";
import { getItemsByConfigId } from "@/api/sb/inspectionItem";
import { getInspectionPlan } from "@/api/sb/inspectionPlan";
import { 
  getByInspectionRecord, 
  getByDate, 
  saveResult, 
  checkCompleted,
  init as initDateRecords
} from "@/api/sb/inspectionDateRecord";

export default {
  name: "ExecuteInspection",
  data() {
    return {
      // 巡检记录ID
      recordId: null,
      // 巡检记录信息
      inspectionRecord: {},
      // 当前选中日期
      currentDate: new Date(),
      // 选中的巡检日期
      selectedDate: null,
      // 选中的日期记录
      selectedDateRecord: null,
      // 巡检日期记录列表
      dateRecords: [],
      // 巡检项目列表
      inspectionItems: [],
      // 表单参数
      form: {
        recordId: null,
        dateRecordId: null,
        inspectionRecordId: null,
        remark: '',
        result: '0',
      },
      // 表单校验规则
      rules: {
        remark: [
          { max: 500, message: "备注最多500个字符", trigger: "blur" }
        ]
      },
      // 状态文本映射
      statusMap: {
        '0': '待巡检',
        '1': '巡检中',
        '2': '已完成',
        '3': '已取消'
      },
      // 状态类型映射
      statusTypeMap: {
        '0': 'info',
        '1': 'warning',
        '2': 'success',
        '3': 'danger'
      },
      // 日期状态映射
      dateStatusMap: {
        '0': '未巡检',
        '1': '已巡检'
      },
      // 日期状态类型映射
      dateStatusTypeMap: {
        '0': 'info',
        '1': 'success'
      },
      // 加载状态
      loading: false,
      // 所有日期是否已完成
      isAllDatesCompleted: false,
      // 暂存的巡检项目
      cachedItems: {},
      // 日历相关数据
      currentMonth: new Date(),
      calendarData: []
    };
  },
  computed: {
    // 状态文本
    statusText() {
      return this.statusMap[this.inspectionRecord.status] || '未知';
    },
    // 状态类型
    statusType() {
      return this.statusTypeMap[this.inspectionRecord.status] || '';
    }
  },
  watch: {
    dateRecords: {
      handler(newVal) {
        console.log("dateRecords发生变化，更新日历数据");
        this.generateCalendarData(this.currentMonth);
      },
      deep: true
    },
    selectedDate(newVal) {
      console.log("selectedDate发生变化:", newVal);
      if (newVal) {
        this.updateCalendarSelection(newVal);
      }
    }
  },
  created() {
    this.recordId = this.$route.params.id;
    if (!this.recordId) {
      this.$message.error("缺少巡检记录ID参数");
      this.goBack();
      return;
    }
    
    console.log("组件created，准备获取巡检记录详情");
    
    // 初始化日历数据
    this.currentMonth = new Date();
    this.generateCalendarData(this.currentMonth);
    
    // 获取巡检记录详情
    this.getRecordDetail();
  },
  mounted() {
    console.log("组件mounted，DOM已渲染完成");
    // 在DOM渲染完成后确保日历单元格可点击
    this.$nextTick(() => {
      this.setupCalendarClickEvents();
    });
  },
  updated() {
    // 在组件更新后重新设置日历点击事件
    this.$nextTick(() => {
      this.setupCalendarClickEvents();
    });
  },
  methods: {
    /** 为日历单元格添加点击事件 */
    setupCalendarClickEvents() {
      console.log("设置日历单元格点击事件");
      // 获取所有日历单元格
      const calendarCells = document.querySelectorAll('.calendar-cell');
      if (calendarCells.length > 0) {
        console.log("找到日历单元格数量:", calendarCells.length);
      } else {
        console.warn("未找到日历单元格");
      }
    },
    /** 获取巡检记录详情 */
    getRecordDetail() {
      this.loading = true;
      getInspectionRecord(this.recordId).then(response => {
        if (response.code === 200) {
          this.inspectionRecord = response.data;
          console.log("获取到巡检记录详情:", this.inspectionRecord);
          console.log("巡检记录中的configId:", this.inspectionRecord.configId);
          
          this.form.inspectionRecordId = this.recordId;
          
          // 如果巡检状态为待巡检，更新为巡检中
          if (this.inspectionRecord.status === '0') {
            this.updateInspectionStatus('1'); // 更新为"巡检中"
          } else if (this.inspectionRecord.status === '2') {
            this.$message.warning("该巡检单已完成，只能查看不能编辑");
            this.goBack();
          } else if (this.inspectionRecord.status === '3') {
            this.$message.warning("该巡检单已取消，不能执行巡检");
            this.goBack();
          }
          
          // 获取巡检日期记录
          this.getDateRecords();
        } else {
          console.error("获取巡检记录详情失败:", response);
          this.$message.error("获取巡检记录详情失败");
          this.loading = false;
        }
      }).catch(err => {
        console.error("获取巡检记录详情出错:", err);
        this.$message.error("获取巡检记录详情出错");
        this.loading = false;
      });
    },
    
    /** 获取巡检日期记录 */
    getDateRecords() {
      getByInspectionRecord(this.recordId).then(response => {
        if (response.code === 200) {
          this.dateRecords = response.data || [];
          console.log("获取到巡检日期记录:", this.dateRecords);
          
          // 如果没有日期记录，初始化
          if (this.dateRecords.length === 0) {
            this.initDateRecords();
          } else {
            // 检查是否所有日期都已完成
            this.checkAllDatesCompleted();

            // 如果有巡检日期记录，默认选中第一个未巡检的日期
            const unfinishedDate = this.dateRecords.find(record => record.status === '0');
            if (unfinishedDate) {
              console.log("自动选择未巡检日期:", unfinishedDate.inspectionDate);
              this.selectedDate = new Date(unfinishedDate.inspectionDate);
              this.currentDate = new Date(unfinishedDate.inspectionDate);
              this.getDateRecord(this.selectedDate);
            }
            
            this.loading = false;
          }
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 初始化巡检日期记录 */
    initDateRecords() {
      initDateRecords(this.recordId).then(response => {
        if (response.code === 200) {
          this.dateRecords = response.data || [];
          console.log("初始化巡检日期记录完成:", this.dateRecords);

          // 如果有巡检日期记录，默认选中第一个
          if (this.dateRecords.length > 0) {
            console.log("自动选择第一个巡检日期:", this.dateRecords[0].inspectionDate);
            this.selectedDate = new Date(this.dateRecords[0].inspectionDate);
            this.currentDate = new Date(this.dateRecords[0].inspectionDate);
            this.getDateRecord(this.selectedDate);
          }
          
          this.loading = false;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 检查是否所有日期都已完成 */
    checkAllDatesCompleted() {
      checkCompleted(this.recordId).then(response => {
        if (response.code === 200) {
          this.isAllDatesCompleted = response.data;
        }
      });
    },
    
    /** 更新巡检状态 */
    updateInspectionStatus(status) {
      const data = {
        recordId: this.recordId,
        status: status
      };
      
      updateInspectionRecord(data).then(response => {
        if (response.code === 200) {
          this.inspectionRecord.status = status;
        }
      });
    },
    
    /** 处理日期选择 */
    handleDatePick(date) {
      console.log("选择日期:", date);
      
      // 确保日期是有效的Date对象并更新selectedDate
      const newDate = new Date(date);
      console.log("处理后的selectedDate:", newDate);
      
      // 重置selectedDate，强制更新显示
      this.selectedDate = null;
      
      // 检查是否是巡检日期
      if (!this.isInspectionDate(newDate)) {
        this.$message.warning("该日期不是巡检日期，请选择有标记的日期");
        return;
      }
      
      // 设置currentDate和selectedDate
      this.$nextTick(() => {
        this.currentDate = newDate;
        this.selectedDate = newDate;
        
        // 检查日期状态
        const dateRecord = this.getDateRecordByDate(this.selectedDate);
        if (dateRecord && dateRecord.status === '1') {
          console.log("选择的是已巡检日期，准备加载已保存的数据:", dateRecord);
        }
        
        this.getDateRecord(this.selectedDate);
      });
    },

    /** 直接点击日期单元格 */
    directDateClick(date) {
      console.log("直接点击日期:", date);
      
      // 确保日期是有效的Date对象并更新selectedDate
      const newDate = new Date(date);
      console.log("处理后的selectedDate:", newDate);
      
      // 重置selectedDate，强制更新显示
      this.selectedDate = null;
      
      // 检查是否是巡检日期
      if (!this.isInspectionDate(newDate)) {
        this.$message.warning("该日期不是巡检日期，请选择有标记的日期");
        return;
      }
      
      // 设置currentDate和selectedDate
      this.$nextTick(() => {
        this.currentDate = newDate;
        this.selectedDate = newDate;
        
        // 检查日期状态
        const dateRecord = this.getDateRecordByDate(this.selectedDate);
        if (dateRecord && dateRecord.status === '1') {
          console.log("选择的是已巡检日期，准备加载已保存的数据:", dateRecord);
        }
        
        this.getDateRecord(this.selectedDate);
      });
    },
    
    /** 获取巡检日期记录 */
    getDateRecord(date) {
      // 如果日期不在巡检日期列表中，不处理
      if (!this.isInspectionDate(date)) {
        this.selectedDateRecord = null;
        this.inspectionItems = [];
        return;
      }
      
      this.loading = true;
      // 格式化日期为 yyyy-MM-dd 并强制更新selectedDate
      const formattedDate = this.parseTime(date, '{y}-{m}-{d}');
      console.log("获取巡检日期记录，date参数:", date, "格式化后:", formattedDate);
      
      // 确保selectedDate被更新，强制UI刷新
      this.selectedDate = new Date(date);
      console.log("更新selectedDate为:", this.selectedDate, "格式化后:", this.parseTime(this.selectedDate, '{y}-{m}-{d}'));
      
      // 从缓存中恢复
      if (this.cachedItems[formattedDate]) {
        console.log("从缓存获取数据:", formattedDate);
        this.selectedDateRecord = this.cachedItems[formattedDate].record;
        
        // 处理缓存的巡检项目，确保有isPassed字段
        this.inspectionItems = this.cachedItems[formattedDate].items.map(item => {
          return {
            ...item,
            isPassed: item.isPassed !== undefined ? item.isPassed : (item.result === '1')
          };
        });
        
        this.form.recordId = this.selectedDateRecord.recordId;
        this.form.dateRecordId = this.selectedDateRecord.recordId;
        this.form.remark = this.selectedDateRecord.remark || '';
        this.loading = false;
        return;
      }
      
      console.log("调用getByDate API，参数:", this.recordId, formattedDate);
      
      // 直接调用API获取日期记录
      getByDate(this.recordId, formattedDate).then(response => {
        console.log("getByDate API响应:", response);
        if (response.code === 200 && response.data) {
          this.selectedDateRecord = response.data;
          this.form.recordId = this.selectedDateRecord.recordId;
          this.form.dateRecordId = this.selectedDateRecord.recordId;
          this.form.remark = this.selectedDateRecord.remark || '';
          this.form.result = this.selectedDateRecord.result || '0';
          
          // 如果有巡检明细，直接使用
          if (this.selectedDateRecord.detailList && this.selectedDateRecord.detailList.length > 0) {
            console.log("使用日期记录中的巡检明细:", this.selectedDateRecord.detailList);
            
            // 处理巡检明细，确保所有必要字段存在
            this.inspectionItems = this.selectedDateRecord.detailList.map(item => {
              return {
                ...item,
                isPassed: item.result === '1', // 结果为1表示通过
                remark: item.remark || '',
                standardValue: item.standardValue || item.itemStandard || item.normalRange || '-',
                dateRecordId: this.selectedDateRecord.recordId,
                inspectionRecordId: this.recordId
              };
            });
            
            console.log("处理后的巡检项目:", this.inspectionItems);
          } else {
            // 否则，获取巡检项目列表
            console.log("日期记录中没有巡检明细，获取巡检项目列表");
            this.getInspectionItems();
          }
        } else {
          console.log("获取日期记录失败，使用默认巡检项目");
          this.getInspectionItems();
        }
        this.loading = false;
      }).catch(err => {
        console.error("getByDate API错误:", err);
        this.$message.error("获取巡检日期记录出错: " + (err.message || "未知错误"));
        this.getInspectionItems(); // 失败时也尝试获取巡检项目
        this.loading = false;
      });
    },
    
    /** 获取巡检项目列表 */
    getInspectionItems() {
      console.log("获取巡检项目，inspectionRecord:", this.inspectionRecord);
      
      // 方法1：如果有巡检配置ID，直接通过配置ID获取巡检项
      if (this.inspectionRecord.configId) {
        console.log("通过configId获取巡检项:", this.inspectionRecord.configId);
        this.loading = true;
        getItemsByConfigId(this.inspectionRecord.configId).then(response => {
          console.log("getItemsByConfigId响应:", response);
          if (response.code === 200 && response.data && response.data.length > 0) {
            this.inspectionItems = response.data;
            // 初始化巡检项结果
            this.initInspectionItems();
          } else {
            console.error("通过configId获取巡检项为空或失败:", response);
            // 尝试方法2
            this.getItemsFromPlan();
          }
          this.loading = false;
        }).catch(err => {
          console.error("获取巡检项出错:", err);
          // 尝试方法2
          this.getItemsFromPlan();
          this.loading = false;
        });
        return;
      } else {
        console.warn("巡检记录中没有configId，尝试其他方法获取巡检项");
      }
      
      // 方法2：如果没有巡检配置ID，通过记录ID获取巡检明细
      console.log("没有configId，通过recordId获取巡检明细:", this.recordId);
      this.loading = true;
      getDetailsByRecordId(this.recordId).then(response => {
        console.log("getDetailsByRecordId响应:", response);
        if (response.code === 200 && response.data && response.data.length > 0) {
          this.inspectionItems = response.data;
          // 初始化巡检项结果
          this.initInspectionItems();
          this.loading = false;
        } else {
          console.warn("通过recordId获取巡检明细为空，尝试从计划中获取");
          // 尝试方法3
          this.getItemsFromPlan();
        }
      }).catch(err => {
        console.error("获取巡检明细出错:", err);
        // 尝试方法3
        this.getItemsFromPlan();
        this.loading = false;
      });
    },
    
    /** 从巡检计划获取巡检项 */
    getItemsFromPlan() {
      // 确保有计划ID
      if (!this.inspectionRecord.planId) {
        console.error("没有巡检计划ID，无法获取巡检项");
        this.$message.error("无法获取巡检项目，请联系管理员");
        this.loading = false;
        return;
      }
      
      // 获取巡检计划
      this.loading = true;
      console.log("通过planId获取巡检计划:", this.inspectionRecord.planId);
      
      getInspectionPlan(this.inspectionRecord.planId).then(response => {
        console.log("获取巡检计划响应:", response);
        if (response.code === 200 && response.data) {
          // 处理新的数据结构
          let plan;
          if (response.data.planInfo) {
            // 新的数据结构，包含planInfo
            plan = response.data.planInfo;
            console.log("使用新的数据结构，从planInfo获取计划数据:", plan);
            
            // 如果有巡检项目，直接使用
            if (response.data.inspectionItems && response.data.inspectionItems.length > 0) {
              console.log("直接使用返回的巡检项目:", response.data.inspectionItems);
              this.inspectionItems = response.data.inspectionItems;
              this.initInspectionItems();
              this.loading = false;
              return;
            }
          } else {
            // 旧的数据结构，直接使用
            plan = response.data;
            console.log("使用旧的数据结构:", plan);
          }
          
          // 获取巡检配置ID
          const configId = plan.configId;
          if (configId) {
            console.log("从计划中获取到configId:", configId);
            
            // 使用配置ID获取巡检项
            getItemsByConfigId(configId).then(resp => {
              console.log("通过计划中的configId获取巡检项响应:", resp);
              if (resp.code === 200 && resp.data && resp.data.length > 0) {
                this.inspectionItems = resp.data;
                // 初始化巡检项结果
                this.initInspectionItems();
              } else {
                console.error("通过计划中的configId获取巡检项失败:", resp);
                this.$message.error("获取巡检项目失败");
              }
              this.loading = false;
            }).catch(err => {
              console.error("通过计划中的configId获取巡检项出错:", err);
              this.$message.error("获取巡检项目出错");
              this.loading = false;
            });
          } else {
            console.error("计划中没有配置ID");
            this.$message.error("巡检计划未关联巡检配置");
            this.loading = false;
          }
        } else {
          console.error("获取巡检计划失败:", response);
          this.$message.error("获取巡检计划失败");
          this.loading = false;
        }
      }).catch(err => {
        console.error("获取巡检计划出错:", err);
        this.$message.error("获取巡检计划出错");
        this.loading = false;
      });
    },
    
    /** 初始化巡检项结果 */
    initInspectionItems() {
      console.log("初始化巡检项目，当前项目数:", this.inspectionItems.length);
      
      this.inspectionItems = this.inspectionItems.map(item => {
        // 默认通过为true，如果有已保存的结果则使用
        const isPassed = item.result ? item.result === '1' : true;
        
        return {
          ...item,
          isPassed: isPassed, // 添加是否通过的标志
          remark: item.remark || '',
          dateRecordId: this.selectedDateRecord ? this.selectedDateRecord.recordId : null,
          inspectionRecordId: this.recordId,
          // 确保标准值字段存在
          standardValue: item.standardValue || item.itemStandard || item.normalRange || '-'
        };
      });
      
      // 打印巡检项目
      console.log("初始化后的巡检项目:", this.inspectionItems);
    },
    
    /** 保存当前日期巡检结果 */
    saveDateResult() {
      // 直接调用后端API，不依赖表单验证
      if (!this.selectedDateRecord) {
        this.$message.error("请先选择巡检日期");
        return;
      }
      
      // 检查巡检项目列表
      if (!this.inspectionItems || this.inspectionItems.length === 0) {
        this.$message.error("没有巡检项目可保存");
        return;
      }
      
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '正在保存巡检结果...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 计算巡检结果：如果所有项目都通过，则为正常，否则为异常
        const allPassed = this.inspectionItems.every(item => item.isPassed);
        
        // 准备要保存的数据
        const saveData = {
          recordId: this.selectedDateRecord.recordId,
          inspectionRecordId: this.recordId,
          remark: this.form.remark || '',
          result: allPassed ? '0' : '1', // 全部通过为正常(0)，否则为异常(1)
          status: '1', // 已巡检
          detailList: []
        };
        
        // 处理巡检项目
        for (let i = 0; i < this.inspectionItems.length; i++) {
          const item = this.inspectionItems[i];
          saveData.detailList.push({
            dateRecordId: this.selectedDateRecord.recordId,
            itemId: item.itemId || 0,
            itemName: item.itemName || '',
            standardValue: item.standardValue || item.itemStandard || '',
            measuredValue: '', // 不再需要实际值
            result: item.isPassed ? '1' : '0', // 通过为1，未通过为0
            remark: item.remark || ''
          });
        }
        
        // 发送请求
        saveResult(saveData)
          .then(response => {
            loading.close();
            if (response.code === 200) {
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              this.getDateRecords(); // 刷新日期状态
              
              // 判断巡检结果是否为异常(值为"1")
              if (saveData.result === '1') {
                // 弹出确认窗口询问是否需要立即报修
                this.$confirm('巡检结果异常，是否需要立即报修？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  // 用户点击确定，跳转到新增报修单页面
                  this.$router.push('/sb/repair-application/add');
                }).catch(() => {
                  // 用户点击取消，不做操作
                });
              }
            } else {
              this.$message.error('保存失败：' + (response.msg || '未知错误'));
            }
          })
          .catch(error => {
            loading.close();
            this.$message.error('保存请求发生错误：' + (error.message || JSON.stringify(error)));
            console.error('保存请求错误:', error);
          });
      } catch (err) {
        loading.close();
        this.$message.error('保存过程出错：' + (err.message || JSON.stringify(err)));
        console.error('保存过程错误:', err);
      }
    },
    
    /** 提交巡检表单 */
    submitForm() {
      // 检查是否所有日期都已完成
      checkCompleted(this.recordId).then(response => {
        if (response.code === 200) {
          const isCompleted = response.data;
          
          // 构建确认消息
          let confirmMessage = "确认要提交此巡检单吗？";
          if (!isCompleted) {
            confirmMessage = "还有未完成的巡检日期，确定要提交整个巡检单吗？";
          }
          
          // 显示确认对话框，更明确的交互
          this.$confirm(confirmMessage, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            closeOnClickModal: false
          }).then(() => {
            // 记录日志
            console.log("用户确认提交巡检单，recordId:", this.recordId, "isAllDatesCompleted:", isCompleted);
            this.submitInspection();
          }).catch(() => {
            // 记录用户取消提交
            console.log("用户取消提交巡检单");
          });
        } else {
          this.$message.error("检查巡检完成状态失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("检查巡检完成状态出错:", error);
        this.$message.error("无法检查巡检完成状态: " + (error.message || "未知错误"));
      });
    },
    
    /** 提交巡检 */
    submitInspection() {
      const loading = this.$loading({
        lock: true,
        text: '正在提交巡检结果...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 更新巡检单状态为已完成
      const data = {
        recordId: this.recordId,
        status: '2', // 已完成
        endTime: new Date()
      };
      
      updateInspectionRecord(data).then(response => {
        loading.close();
        if (response.code === 200) {
          this.$message.success("巡检已完成");
          
          // 延迟执行跳转，给后端足够时间处理数据
          setTimeout(() => {
            // 保存正确的导航路径
            const targetPath = "/sb/Inspection-list";
            
            console.log("提交成功，准备导航到:", targetPath);
            
            try {
              // 首先尝试使用router.replace并传递刷新参数
              this.$router.replace({
                path: targetPath,
                query: { refresh: new Date().getTime() }
              }).then(() => {
                console.log("导航成功，已添加刷新参数");
              }).catch(err => {
                console.error("Router replace 导航失败:", err);
                
                try {
                  // 如果router.replace失败，尝试使用router.push
                  this.$router.push({
                    path: targetPath,
                    query: { refresh: new Date().getTime() }
                  }).then(() => {
                    console.log("Router push 导航成功");
                  }).catch(err2 => {
                    console.error("Router push 导航也失败:", err2);
                    // 最后尝试window.location
                    window.location.href = targetPath + "?refresh=" + new Date().getTime();
                  });
                } catch (error) {
                  console.error("Router push 异常:", error);
                  window.location.href = targetPath + "?refresh=" + new Date().getTime();
                }
              });
            } catch (err) {
              console.error("导航过程发生异常:", err);
              // 兜底方案，直接使用location
              window.location.href = targetPath + "?refresh=" + new Date().getTime();
            }
          }, 1000); // 增加延迟时间到1秒
        } else {
          this.$message.error("提交失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        loading.close();
        this.$message.error("提交出错: " + (error.message || JSON.stringify(error)));
        console.error("提交巡检单错误:", error);
      });
    },
    
    /** 判断是否是巡检日期 */
    isInspectionDate(date) {
      const formattedDate = this.parseTime(date, '{y}-{m}-{d}');
      return this.dateRecords.some(record => 
        this.parseTime(record.inspectionDate, '{y}-{m}-{d}') === formattedDate
      );
    },
    
    /** 获取日期类名 */
    getDateClass(date) {
      const classes = [];
      
      if (this.isInspectionDate(date)) {
        classes.push('inspection-date');
        
        // 检查是否是已完成的巡检日期 - 已巡检日期使用不同的样式，但仍可点击修改
        const record = this.getDateRecordByDate(date);
        if (record && record.status === '1') {
          classes.push('completed-date');
        }
        
        // 检查是否是当前选中日期
        if (this.selectedDate && 
            this.parseTime(date, '{y}-{m}-{d}') === this.parseTime(this.selectedDate, '{y}-{m}-{d}')) {
          classes.push('selected-date');
        }
      }
      
      return classes.join(' ');
    },
    
    /** 根据日期获取日期记录 */
    getDateRecordByDate(date) {
      const formattedDate = this.parseTime(date, '{y}-{m}-{d}');
      console.log("查找日期记录，格式化日期:", formattedDate);
      
      // 找到匹配的日期记录
      const record = this.dateRecords.find(record => 
        this.parseTime(record.inspectionDate, '{y}-{m}-{d}') === formattedDate
      );
      
      if (record) {
        console.log("找到匹配的日期记录:", record.recordId, this.parseTime(record.inspectionDate, '{y}-{m}-{d}'));
      } else {
        console.log("未找到匹配的日期记录，formattedDate:", formattedDate);
      }
      
      return record;
    },
    
    /** 获取日期状态文本 */
    getDateStatusText(date) {
      const record = this.getDateRecordByDate(date);
      return record ? this.dateStatusMap[record.status] : '';
    },
    
    /** 获取日期状态类型 */
    getDateStatusType(date) {
      const record = this.getDateRecordByDate(date);
      return record ? this.dateStatusTypeMap[record.status] : '';
    },
    
    /** 返回按钮 */
    goBack() {
      // 首先检查是否有未保存的巡检数据
      if (this.isFormDirty) {
        this.$confirm('有未保存的巡检数据，确定要离开吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 判断是否从列表页进入
          if (this.$route.query.fromList) {
            this.$router.push({ 
              path: '/sb/Inspection-list',
              query: { refresh: true }
            });
          } else {
            this.$router.go(-1);
          }
        }).catch(() => {
          // 用户取消，不做操作
        });
      } else {
        // 没有未保存数据，直接返回
        // 判断是否从列表页进入
        if (this.$route.query.fromList) {
          this.$router.push({ 
            path: '/sb/Inspection-list',
            query: { refresh: true }
          });
        } else {
          this.$router.go(-1);
        }
      }
    },

    /** 日历单元格点击事件 */
    handleCellClick(day) {
      console.log("日历单元格点击:", day);
      
      // 忽略空单元格和非当月日期
      if (!day.date || !day.isCurrentMonth) {
        return;
      }
      
      // 直接使用dateObj
      const newDate = day.dateObj || new Date(day.date);
      console.log("点击单元格，日期对象:", newDate);
      
      // 检查是否是巡检日期
      if (!this.isInspectionDate(newDate)) {
        this.$message.warning("该日期不是巡检日期，请选择有标记的日期");
        return;
      }
      
      // 重置selectedDate，强制更新显示
      this.selectedDate = null;
      
      // 设置currentDate和selectedDate
      this.$nextTick(() => {
        this.currentDate = newDate;
        this.selectedDate = newDate;
        
        // 更新日历选中状态
        this.updateCalendarSelection(newDate);
        
        // 检查日期状态
        const dateRecord = this.getDateRecordByDate(this.selectedDate);
        if (dateRecord && dateRecord.status === '1') {
          console.log("选择的是已巡检日期，准备加载已保存的数据:", dateRecord);
        }
        
        this.getDateRecord(this.selectedDate);
      });
    },
    
    /** 更新日历选中状态 */
    updateCalendarSelection(date) {
      const formattedDate = this.parseTime(date, '{y}-{m}-{d}');
      console.log("更新日历选中状态:", formattedDate);
      
      // 遍历日历数据，更新选中状态
      this.calendarData.forEach(week => {
        week.forEach(day => {
          if (day.date) {
            const dayDateParts = day.date.split('-');
            const dayYear = parseInt(dayDateParts[0]);
            const dayMonth = parseInt(dayDateParts[1]);
            const dayDay = parseInt(dayDateParts[2]);
            const dayDate = new Date(dayYear, dayMonth - 1, dayDay);
            
            // 更新选中状态
            day.isSelected = this.parseTime(dayDate, '{y}-{m}-{d}') === formattedDate;
          }
        });
      });
    },
    
    /** 切换月份 */
    changeMonth(delta) {
      const newDate = new Date(this.currentMonth);
      newDate.setMonth(newDate.getMonth() + delta);
      this.currentMonth = newDate;
      this.generateCalendarData(newDate);
    },

    /** 生成日历数据 */
    generateCalendarData(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      const firstDayOfMonth = new Date(year, month, 1);
      const lastDayOfMonth = new Date(year, month + 1, 0);
      const daysInMonth = lastDayOfMonth.getDate();
      const firstDayOfWeek = firstDayOfMonth.getDay(); // 0 for Sunday, 6 for Saturday

      const calendar = [];
      let week = [];

      // Add empty cells for days before the first day of the month
      for (let i = 0; i < firstDayOfWeek; i++) {
        week.push({ date: '', isToday: false, isInspection: false, isCompleted: false, isSelected: false, isCurrentMonth: false });
      }

      // Add days of the month
      for (let i = 1; i <= daysInMonth; i++) {
        const currentDate = new Date(year, month, i);
        const isToday = this.isToday(currentDate);
        const isInspection = this.isInspectionDate(currentDate);
        const dateRecord = this.getDateRecordByDate(currentDate);
        const isCompleted = dateRecord ? dateRecord.status === '1' : false;
        const isSelected = this.selectedDate && this.parseTime(currentDate, '{y}-{m}-{d}') === this.parseTime(this.selectedDate, '{y}-{m}-{d}');
        
        // Format date string as yyyy-MM-dd
        const monthStr = (month + 1).toString().padStart(2, '0');
        const dayStr = i.toString().padStart(2, '0');
        const dateStr = `${year}-${monthStr}-${dayStr}`;
        
        week.push({ 
          date: dateStr, 
          dateObj: currentDate,
          dayOfMonth: i, 
          isToday, 
          isInspection, 
          isCompleted, 
          isSelected, 
          isCurrentMonth: true 
        });

        if (week.length === 7) {
          calendar.push(week);
          week = [];
        }
      }

      // Add empty cells for days after the last day of the month
      if (week.length > 0) {
        for (let i = week.length; i < 7; i++) {
          week.push({ date: '', isToday: false, isInspection: false, isCompleted: false, isSelected: false, isCurrentMonth: false });
        }
        calendar.push(week);
      }

      console.log("生成日历数据完成:", calendar);
      this.calendarData = calendar;
    },

    /** 判断是否是今天 */
    isToday(date) {
      const today = new Date();
      return this.parseTime(date, '{y}-{m}-{d}') === this.parseTime(today, '{y}-{m}-{d}');
    },

    /** 巡检项目结果变化 */
    handleCheckboxChange(item) {
      console.log("巡检项目结果变化:", item);
      // 当巡检结果变化时，更新巡检明细中的result字段
      if (this.selectedDateRecord && this.selectedDateRecord.detailList) {
        const detailItem = this.selectedDateRecord.detailList.find(
          (detail) => detail.itemId === item.itemId
        );
        if (detailItem) {
          detailItem.result = item.isPassed ? '1' : '0'; // 通过为1，未通过为0
        }
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.el-divider {
  margin: 20px 0;
}
.el-table {
  margin-bottom: 20px;
}
.calendar-container {
  margin: 20px 0;
}
.simple-calendar {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fff;
}
.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}
.month-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
.calendar-table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
}
.calendar-table th,
.calendar-table td {
  text-align: center;
  padding: 10px 0;
  border: 1px solid #ebeef5;
  width: calc(100% / 7); /* 7 columns */
}
.calendar-table th {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #606266;
}
.calendar-table td {
  cursor: pointer;
  transition: background-color 0.3s;
}
.calendar-table td:hover {
  background-color: #f0f9eb; /* 浅绿色背景 */
}
.calendar-table td.is-today {
  background-color: #e1f3d8; /* 更深的浅绿色 */
  border-radius: 50%;
  width: 36px; /* 调整大小以适应圆形 */
  height: 36px; /* 调整大小以适应圆形 */
  line-height: 36px; /* 调整大小以适应圆形 */
  margin: 0 auto; /* 居中 */
}
.calendar-table td.inspection-date {
  background-color: #f0f9eb; /* 浅绿色背景 */
  border-radius: 4px;
  cursor: pointer !important; /* 强制添加手型光标，表示可点击 */
  transition: all 0.3s; /* 添加过渡效果 */
  position: relative;
  z-index: 20;
}
.calendar-table td.inspection-date:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.calendar-table td.completed-date {
  background-color: #ecf5ff; /* 浅蓝色背景 */
  border: 1px dashed #409EFF; /* 添加虚线边框，表示已完成 */
}
.calendar-table td.completed-date:hover {
  background-color: #d9ecff; /* 鼠标悬停时变色，提示可以修改 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}
.calendar-table td.selected-date {
  background-color: #fef0f0;
  font-weight: bold;
  border: 2px solid #F56C6C; /* 给选中的日期添加明显的边框 */
}
.calendar-table td.other-month {
  color: #c0c4cc; /* 非当前月份的日期颜色 */
  background-color: #f5f7fa; /* 非当前月份的背景 */
}
.calendar-table td .cell-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.calendar-table td .date-text {
  font-size: 14px;
  color: #303133;
}
.calendar-table td .inspection-tag {
  margin-top: 5px;
  font-size: 12px;
  color: #67c23a; /* 绿色标签 */
  background-color: #f0f9eb;
  border-radius: 4px;
  padding: 2px 6px;
}
.calendar-table td .inspection-tag.is-completed {
  color: #909399; /* 灰色标签 */
  background-color: #f4f4f4;
  border: 1px solid #ebeef5;
}
.selected-date-info {
  margin-bottom: 20px;
}
</style> 